import { get, post, put, del } from '../services/api';
import { API } from '../constants';
import type { UserData, UsersListResponse } from '../types';

/**
 * 示例：如何使用封装的API请求方法
 */

// 示例1：登录
async function loginExample(username: string, password: string) {
  const response = await post(API.AUTH.LOGIN, { username, password });
  
  if (response.success && response.data) {
    console.log('登录成功:', response.data);
    return response.data;
  } else {
    console.error('登录失败:', response.message);
    return null;
  }
}

// 示例2：获取用户列表（带类型参数）
async function getUsersExample() {
  const response = await get<UsersListResponse>(API.USERS.LIST, { page: 1, pageSize: 10 });
  
  if (response.success && response.data) {
    const { users, totalCount } = response.data;
    console.log(`共有 ${totalCount} 个用户`);
    return users;
  } else {
    console.error('获取用户列表失败:', response.message);
    return [];
  }
}

// 示例3：创建用户
async function createUserExample(userData: { username: string; password: string; displayName: string; role: string }) {
  const response = await post<UserData>(API.USERS.CREATE, userData);
  
  if (response.success && response.data) {
    console.log('用户创建成功:', response.data);
    return response.data;
  } else {
    console.error('创建用户失败:', response.message);
    return null;
  }
}

// 示例4：更新用户
async function updateUserExample(username: string, userData: { displayName?: string; email?: string }) {
  const response = await put<UserData>(API.USERS.UPDATE(username), userData);
  
  if (response.success && response.data) {
    console.log('用户更新成功:', response.data);
    return response.data;
  } else {
    console.error('更新用户失败:', response.message);
    return null;
  }
}

// 示例5：删除用户
async function deleteUserExample(username: string) {
  const response = await del(API.USERS.DELETE(username));
  
  if (response.success) {
    console.log('用户删除成功');
    return true;
  } else {
    console.error('删除用户失败:', response.message);
    return false;
  }
}

// 示例6：使用自定义配置
async function customConfigExample() {
  // 不显示错误消息
  const response = await get(API.USERS.LIST, { page: 1 }, { showErrorMessage: false });
  
  // 添加自定义请求头
  const responseWithHeaders = await post(
    API.AUTH.LOGIN, 
    { username: 'admin', password: 'password' },
    { headers: { 'X-Custom-Header': 'value' } }
  );
  
  return { response, responseWithHeaders };
}

export {
  loginExample,
  getUsersExample,
  createUserExample,
  updateUserExample,
  deleteUserExample,
  customConfigExample
}; 